<template>
  <div class="device-status-box">
    <!-- 左侧组织架构菜单 -->
    <el-card class="content__left">
      <realtimemonito-menu :data="menus" v-model:menu-id="menuId" v-model:open-id="openId" @menu-click="commEvent.menuClick" />
    </el-card>

    <!-- 右侧设备状态展示 -->
    <el-card class="content__right">
      <!-- 状态图例 -->
      <div class="status-legend">
        <div class="legend-item">
          <div class="legend-icon running"></div>
          <span>运行中</span>
        </div>
        <div class="legend-item">
          <div class="legend-icon standby"></div>
          <span>待机</span>
        </div>
        <div class="legend-item">
          <div class="legend-icon stopped"></div>
          <span>停机</span>
        </div>
        <div class="legend-item">
          <div class="legend-icon abnormal"></div>
          <span>异常</span>
        </div>
      </div>

      <!-- 产线网格 -->
      <div class="production-line-grid">
        <div v-for="line in productionLines" :key="line.id" class="line-card">
          <!-- 左侧：产线图片和信息 -->
          <div class="line-left">
            <div class="line-image">
              <img src="@/assets/images/cxi.png" alt="产线图片" />
            </div>
            <h3 class="line-name">{{ line.name }}</h3>
            <div class="line-stats" v-if="line.devices.length > 0">
              <div class="stat-row">
                <span class="stat-label">运行</span>
                <span class="stat-dot running"></span>
                <span class="stat-count">{{ getLineDeviceCount(line, 3) }}</span>
              </div>
              <div class="stat-row">
                <span class="stat-label">待机</span>
                <span class="stat-dot standby"></span>
                <span class="stat-count">{{ getLineDeviceCount(line, 2) }}</span>
              </div>
              <div class="stat-row">
                <span class="stat-label">停机</span>
                <span class="stat-dot stopped"></span>
                <span class="stat-count">{{ getLineDeviceCount(line, 1) }}</span>
              </div>
              <div class="stat-row">
                <span class="stat-label">异常</span>
                <span class="stat-dot abnormal"></span>
                <span class="stat-count">{{ getLineDeviceCount(line, 9) }}</span>
              </div>
            </div>
            <div class="line-stats no-device" v-else>
              <span class="stat-label">暂无设备</span>
            </div>
          </div>

          <!-- 右侧：设备列表（滚动展示）-->
          <div class="line-right">
            <div v-if="line.devices.length > 0" class="devices-scroll">
              <div class="devices-wrapper">
                <div
                  v-for="device in line.devices"
                  :key="device.id"
                  class="device-item"
                  @click="commEvent.showDeviceDetail(device)"
                >
                  <div class="device-name">{{ device.name }}</div>
                  <div class="device-status-dot" :class="getDeviceStatusClass(device.runState)"></div>
                </div>
              </div>
            </div>
            <div v-else class="no-devices">暂无设备</div>
          </div>
        </div>
      </div>
      <el-empty v-if="!productionLines.length" description="暂无产线数据" />
    </el-card>

    <!-- 设备详情弹窗 -->
    <el-dialog title="设备详情" v-model="detailVisible" width="600px" append-to-body>
      <div class="device-detail" v-if="currentDevice">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备名称">{{ currentDevice.name }}</el-descriptions-item>
          <el-descriptions-item label="设备编码">{{ currentDevice.code }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ currentDevice.deviceTypeName }}</el-descriptions-item>
          <el-descriptions-item label="运行状态">
            <el-tag :type="getStatusTagType(currentDevice.runState)">
              {{ getStatusText(currentDevice.runState) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="安装位置">{{ currentDevice.location }}</el-descriptions-item>
          <el-descriptions-item label="规格型号">{{ currentDevice.modelNumber }}</el-descriptions-item>
          <el-descriptions-item label="生产厂家">{{ currentDevice.manufacturer }}</el-descriptions-item>
          <el-descriptions-item label="负责人">{{ currentDevice.personCharge }}</el-descriptions-item>
        </el-descriptions>

        <!-- 统计数据 -->
        <div class="statistics-section">
          <h4>运行统计</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-label">转产次数</div>
                <div class="stat-value">{{ currentDevice.switchCount || 0 }}次</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-label">开机率</div>
                <div class="stat-value">{{ ((currentDevice.startRate || 0) * 100).toFixed(1) }}%</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-label">异常停机总时长</div>
                <div class="stat-value abnormal">{{ currentDevice.abnormalStopTime || 0 }}h</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-label">计划停机总时长</div>
                <div class="stat-value planned">{{ currentDevice.plannedStopTime || 0 }}h</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <template #footer>
        <div style="text-align: center">
          <el-button @click="detailVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue"
import RealtimemonitoMenu, { MenuType } from "../abnormal/analysis/components/RealtimemonitoMenu.vue"
import { organTree } from "@/api/modules/system"
import { SystemSpace as SystemApi } from "@/api/interface/system"
import { devicePage } from "@/api/modules/archive"
import { SystemSpace as SystemArchive } from "@/api/interface/archive"
import { dataDictionaryByType } from "@/api/modules/system"
const deviceTypeEnum = ref<any[]>([]) // 设备类型

// 设备扩展接口（包含统计数据）
interface DeviceWithStats extends SystemArchive.DevicePage {
  switchCount?: number // 转产次数
  startRate?: number // 开机率
  abnormalStopTime?: number // 异常停机总时长
  plannedStopTime?: number // 计划停机总时长
  deviceTypeName?: string // 设备类型名称
}

// 产线接口
interface ProductionLine {
  id: number
  name: string
  devices: DeviceWithStats[]
}

// 参数
const menuValue = ref({
  factoryId: undefined as undefined | number,
  lineId: undefined as undefined | number
})
const openId = ref<number[]>([]) // 菜单展开id
const menuId = ref<number>(-1) // 菜单选中id
const menus = ref<MenuType[]>([]) // 菜单树结构
const devices = ref<DeviceWithStats[]>([]) // 设备信息
const productionLines = ref<ProductionLine[]>([]) // 产线信息
const detailVisible = ref(false) // 详情弹窗
const currentDevice = ref<DeviceWithStats>() // 当前选中设备

// 页码参数
const pageParams = ref({
  pageIndex: 1,
  pageSize: 1000 // 获取更多设备用于展示
})

// 事件
const commEvent = {
  // 获取菜单信息
  getMenus: async () => {
    const { data } = await organTree()
    menus.value = commEvent.formatMenu(data)
    if (data && data.length > 0) {
      const _id: number = data[0].id
      menuId.value = _id
      openId.value = [_id]
      menuValue.value.factoryId = _id
    }
    commEvent.getDevices()
  },

  // 格式化菜单树
  formatMenu: (data: SystemApi.OrganTree[], pids?: number[]): any[] => {
    if (!data || data.length <= 0) return []
    return data.map(item => {
      let pidArr: number[] = []
      if (pids) {
        pidArr = [...pids, item.pid || 0]
      }
      return {
        id: item.id,
        text: item.organName,
        level: item.level,
        pid: item.pid,
        pidArr,
        children: commEvent.formatMenu(item.childrenTree || [], pidArr)
      }
    })
  },

  // 菜单点击
  menuClick: (item: any) => {
    if (item.level === 1) {
      menuValue.value.factoryId = item.id
      menuValue.value.lineId = undefined
    } else if (item.level === 2) {
      menuValue.value.factoryId = item.pid
      menuValue.value.lineId = item.id
    } else {
      menuValue.value.factoryId = undefined
      menuValue.value.lineId = undefined
    }
    commEvent.getDevices()
  },

  // 获取设备信息
  getDevices: async () => {
    try {
      const params = {
        ...pageParams.value,
        factoryId: menuValue.value.factoryId ? String(menuValue.value.factoryId) : undefined,
        lineId: menuValue.value.lineId ? String(menuValue.value.lineId) : undefined
      }
      const { data } = await devicePage(params)

      // 设置基本设备信息
      devices.value = data.result.map((device: SystemArchive.DevicePage) => ({
        ...device,
        deviceTypeName: getDeviceTypeName(device.deviceType)
      }))

      // commEvent.addMockDevices()

      // 按产线分组设备
      commEvent.groupDevicesByLine()
    } catch (error) {
      console.error("获取设备失败：", error)
    }
  },

  // 添加模拟设备数据（测试用）
  addMockDevices: () => {
    if (devices.value.length === 0) return

    const mockDevices: DeviceWithStats[] = []
    const statusList = [1, 2, 3, 9] // 停机、待机、运行中、异常

    // 为每个已有设备的产线添加15个模拟设备（增加数量以测试滚动）
    const lineIds = new Set(devices.value.map(d => d.lineId).filter(Boolean))

    lineIds.forEach(lineId => {
      for (let i = 1; i <= 2; i++) {
        // 基于第一个设备创建模拟设备
        const baseDevice = devices.value.find(d => d.lineId === lineId) || devices.value[0]
        mockDevices.push({
          ...baseDevice,
          id: Date.now() + Math.random() * 100000, // 生成唯一ID
          name: `测试设备-${lineId}-${String(i).padStart(2, "0")}`,
          code: `MOCK-${lineId}-${String(i).padStart(2, "0")}`,
          runState: statusList[i % statusList.length], // 循环使用不同状态
          lineId: lineId
        })
      }
    })

    devices.value = [...devices.value, ...mockDevices]
  },

  // 按产线分组设备
  groupDevicesByLine: () => {
    const lineMap = new Map<number, ProductionLine>()

    // 如果选择了具体产线，只显示该产线
    if (menuValue.value.lineId) {
      const lineName = commEvent.getLineName(menuValue.value.lineId)
      lineMap.set(menuValue.value.lineId, {
        id: menuValue.value.lineId,
        name: lineName,
        devices: []
      })
    } else {
      // 如果选择的是工厂，获取该工厂下的所有产线
      const allLines = commEvent.getAllLinesForFactory(menuValue.value.factoryId)
      allLines.forEach(line => {
        lineMap.set(line.id, {
          id: line.id,
          name: line.name,
          devices: []
        })
      })
    }

    // 然后将设备分配到对应的产线
    devices.value.forEach(device => {
      if (device.lineId && lineMap.has(device.lineId)) {
        lineMap.get(device.lineId)!.devices.push(device)
      } else if (device.lineId && !lineMap.has(device.lineId) && !menuValue.value.lineId) {
        // 设备有产线ID，但不在当前工厂的产线列表中，并且当前未选择具体产线时，单独处理
        const lineName = commEvent.getLineName(device.lineId)
        lineMap.set(device.lineId, {
          id: device.lineId,
          name: lineName,
          devices: [device]
        })
      } else if (!device.lineId && !menuValue.value.lineId) {
        // 没有产线ID的设备放到"未分配产线"组（仅在工厂视图下显示）
        const unassignedId = -1
        if (!lineMap.has(unassignedId)) {
          lineMap.set(unassignedId, {
            id: unassignedId,
            name: "未分配产线",
            devices: []
          })
        }
        lineMap.get(unassignedId)!.devices.push(device)
      }
    })

    productionLines.value = Array.from(lineMap.values())
  },

  // 获取指定工厂下的所有产线
  getAllLinesForFactory: (factoryId: number | undefined): Array<{ id: number; name: string }> => {
    if (!factoryId) return []

    const lines: Array<{ id: number; name: string }> = []
    const findFactory = (items: MenuType[]): MenuType | null => {
      for (const item of items) {
        if (item.id === factoryId && item.level === 1) {
          return item
        }
        if (item.children && item.children.length > 0) {
          const result = findFactory(item.children)
          if (result) return result
        }
      }
      return null
    }

    const factory = findFactory(menus.value)
    if (factory && factory.children) {
      factory.children.forEach(child => {
        if (child.level === 2) {
          lines.push({
            id: child.id,
            name: child.text
          })
        }
      })
    }

    return lines
  },

  // 从菜单树中获取产线名称
  getLineName: (lineId: number): string => {
    const findLine = (items: MenuType[]): string | null => {
      for (const item of items) {
        if (item.id === lineId && item.level === 2) {
          return item.text
        }
        if (item.children && item.children.length > 0) {
          const result = findLine(item.children)
          if (result) return result
        }
      }
      return null
    }
    return findLine(menus.value) || `产线${lineId}`
  },

  // 显示设备详情
  showDeviceDetail: async (device: DeviceWithStats) => {
    currentDevice.value = device
    detailVisible.value = true

    // 获取设备统计数据
    // console.error("获取设备统计数据失败：", error)
    // 使用默认值
    currentDevice.value = {
      ...currentDevice.value,
      switchCount: 0,
      startRate: 0,
      abnormalStopTime: 0,
      plannedStopTime: 0
    }
    // try {
    //   const { data } = await getDeviceStats(device.id)
    //   currentDevice.value = {
    //     ...currentDevice.value,
    //     ...data
    //   }
    // } catch (error) {

    // }
  },
  // 获取设备类型
  getDeviceType: async () => {
    const { data } = await dataDictionaryByType("device_type")
    deviceTypeEnum.value = data.map(item => ({
      label: item.dictLabel,
      value: Number(item.dictValue),
      dictCode: item.dictCode,
      dictSort: item.dictSort
    }))
  }
}

// 获取设备状态样式类
const getDeviceStatusClass = (runState: number) => {
  switch (runState) {
    case 1:
      return "stopped" // 停机
    case 2:
      return "standby" // 待机
    case 3:
      return "running" // 运行中
    case 9:
      return "abnormal" // 异常
    default:
      return "unknown"
  }
}

// 获取状态文本
const getStatusText = (runState: number) => {
  switch (runState) {
    case 1:
      return "停机"
    case 2:
      return "待机"
    case 3:
      return "运行中"
    case 9:
      return "异常"
    default:
      return "未知"
  }
}

// 获取状态标签类型
const getStatusTagType = (runState: number) => {
  switch (runState) {
    case 1:
      return "info" // 停机
    case 2:
      return "warning" // 待机
    case 3:
      return "success" // 运行中
    case 9:
      return "danger" // 异常
    default:
      return "info"
  }
}

// 获取设备类型名称（从字典数据获取）
const getDeviceTypeName = (deviceType: number) => {
  const typeItem = deviceTypeEnum.value.find(item => item.value === deviceType)
  return typeItem ? typeItem.label : "未知类型"
}

// 获取产线下特定状态的设备数量
const getLineDeviceCount = (line: ProductionLine, runState: number) => {
  return line.devices.filter(device => device.runState === runState).length
}

onMounted(async () => {
  // 先获取设备类型数据，再获取菜单和设备数据
  await commEvent.getDeviceType()
  commEvent.getMenus()
})
</script>

<style lang="scss" scoped>
.device-status-box {
  display: flex;
  width: 100%;
  height: calc(100vh - 140px);
  box-sizing: border-box;
  gap: 10px;
  .content__left {
    width: 200px;
    :deep(.el-card__body) {
      padding: 10px 0 0 0;
      height: 100%;
    }
    height: 100%;
    overflow-y: auto;
    padding: 0 4px; /* 为滚动条留空间 */
    scroll-behavior: smooth;
    /* 滚动条宽度 */
    &::-webkit-scrollbar {
      width: 3px;
    }

    /* 滚动条轨道 */
    &::-webkit-scrollbar-track {
      background: var(--el-fill-color-light);
      border-radius: 3px;
      margin: 2px 0; /* 上下留间距 */
    }
  }

  .content__right {
    box-sizing: border-box;
    flex: 1;
    width: 100%;
    min-width: 0;
    overflow-y: auto;
    background-color: var(--el-bg-color);
    .status-legend {
      display: flex;
      gap: 12px;
      margin-bottom: 12px;
      padding: 10px 12px;
      background: var(--el-fill-color-light);
      border-radius: 6px;

      .legend-item {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 12px;
        color: var(--el-text-color-primary);
        .legend-icon {
          width: 10px;
          height: 10px;
          border-radius: 50%;

          &.running {
            background-color: #67c23a;
          }

          &.standby {
            background-color: #e6a23c;
          }

          &.stopped {
            background-color: #909399;
          }

          &.abnormal {
            background-color: #f56c6c;
          }
        }
      }
    }

    .production-line-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 12px;
      padding: 8px 0;

      .line-card {
        display: flex;
        border: 1px solid var(--el-border-color);
        border-radius: 8px;
        background: var(--el-bg-color);
        transition: all 0.3s;
        overflow: hidden;
        aspect-ratio: 1 / 1;

        &:hover {
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .line-left {
          width: 45%;
          flex-shrink: 0;
          padding: 8px;
          background: var(--el-fill-color-light);
          border-right: 1px solid var(--el-border-color);
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          .line-image {
            width: 80%;
            // aspect-ratio: 1 / 1;
            border-radius: 6px;
            overflow: hidden;
            // border: 1px solid var(--el-border-color);
            margin-bottom: 6px;
            // background: var(--el-fill-color-lighter);
            padding: 3px;
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }

          .line-name {
            font-size: 12px;
            font-weight: 600;
            color: var(--el-text-color-primary);
            margin: 0 0 6px 0;
            text-align: center;
            width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .line-stats {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 4px 6px;
            width: 100%;
            margin-top: 15px;
            &.no-device {
              display: flex;
              justify-content: center;
              align-items: center;
              padding: 6px 0;

              .stat-label {
                color: var(--el-text-color-secondary);
                font-size: 13px;
              }
            }

            .stat-row {
              display: flex;
              align-items: center;
              gap: 3px;
              font-size: 10px;
              padding: 3px 4px;
              border-radius: 3px;
              transition: background 0.2s;

              &:hover {
                background: rgba(0, 0, 0, 0.02);
              }

              .stat-label {
                color: var(--el-text-color-regular);
                min-width: 24px;
                flex-shrink: 0;
                font-size: 10px;
              }

              .stat-dot {
                width: 7px;
                height: 7px;
                border-radius: 50%;
                flex-shrink: 0;

                &.running {
                  background-color: #67c23a;
                }

                &.standby {
                  background-color: #e6a23c;
                }

                &.stopped {
                  background-color: #909399;
                }

                &.abnormal {
                  background-color: #f56c6c;
                }
              }

              .stat-count {
                color: var(--el-text-color-primary);
                font-weight: 600;
                font-size: 11px;
                margin-left: auto;
              }
            }
          }
        }

        .line-right {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;
          background: var(--el-fill-color-light);
          .no-devices {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--el-text-color-secondary);
            font-size: 13px;
          }

          .devices-scroll {
            flex: 1;
            overflow-y: auto;
            padding: 6px;

            /* 滚动条样式 */
            &::-webkit-scrollbar {
              width: 4px;
            }

            &::-webkit-scrollbar-track {
              background: transparent;
            }

            &::-webkit-scrollbar-thumb {
              background: var(--el-border-color);
              border-radius: 2px;

              &:hover {
                background: var(--el-color-primary-light-5);
              }
            }

            .devices-wrapper {
              min-height: 100%;
              display: flex;
              flex-direction: column;
              gap: 4px;

              &::before,
              &::after {
                content: "";
                flex: 1;
              }
            }

            .device-item {
              display: flex;
              align-items: center;
              justify-content: space-between;
              padding: 8px 9px;
              border: 1px solid var(--el-border-color);
              border-radius: 4px;
              cursor: pointer;
              transition: all 0.3s;
              background: var(--el-bg-color);
              flex-shrink: 0;

              &:hover {
                border-color: var(--el-color-primary);
                box-shadow: 0 2px 6px rgba(64, 158, 255, 0.15);
                transform: translateX(2px);
              }

              .device-name {
                flex: 1;
                font-size: 11px;
                color: var(--el-text-color-primary);
                line-height: 1.3;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                padding-right: 6px;
              }

              .device-status-dot {
                width: 8px;
                height: 8px;
                border-radius: 50%;
                flex-shrink: 0;

                &.running {
                  background-color: #67c23a;
                }

                &.standby {
                  background-color: #e6a23c;
                }

                &.stopped {
                  background-color: #909399;
                }

                &.abnormal {
                  background-color: #f56c6c;
                  // animation: blink 1s infinite;
                }
              }
            }
          }
        }
      }
    }
  }
}

.device-detail {
  .statistics-section {
    margin-top: 20px;

    h4 {
      margin-bottom: 15px;
      color: var(--el-text-color-primary);
      font-size: 16px;
      font-weight: 600;
    }

    .stat-item {
      text-align: center;
      padding: 15px;
      background: var(--el-fill-color-light);
      border-radius: 8px;
      margin-bottom: 15px;

      .stat-label {
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin-bottom: 8px;
      }

      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #409eff;

        &.abnormal {
          color: #f56c6c;
        }

        &.planned {
          color: #e6a23c;
        }
      }
    }
  }
}

@keyframes blink {
  0%,
  50% {
    opacity: 1;
  }
  51%,
  100% {
    opacity: 0.3;
  }
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

:deep(.el-descriptions__content) {
  color: var(--el-text-color-regular);
}
</style>
